<template>
  <div class="data-visualization">
    <h1>Data Visualization</h1>
    
    <el-row :gutter="20">
      <el-col :span="8">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>User Statistics</span>
            </div>
          </template>
          <div class="chart-container">
            <div id="userChart" style="width: 100%; height: 300px;"></div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="8">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>Revenue Statistics</span>
            </div>
          </template>
          <div class="chart-container">
            <div id="revenueChart" style="width: 100%; height: 300px;"></div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="8">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>Popular Drugs</span>
            </div>
          </template>
          <div class="chart-container">
            <div id="drugChart" style="width: 100%; height: 300px;"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="12">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>Monthly Treatment Statistics</span>
            </div>
          </template>
          <div class="chart-container">
            <div id="treatmentChart" style="width: 100%; height: 300px;"></div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="12">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>Popular Medical Checks</span>
            </div>
          </template>
          <div class="chart-container">
            <div id="checksChart" style="width: 100%; height: 300px;"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { onMounted, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts/core'
import { PieChart, BarChart, LineChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'
import { useUserStore } from '../../stores/users'
import { useDrugStore } from '../../stores/drug'
import { useCheckStore } from '../../stores/checks'
import { useOrderStore } from '../../stores/orders'

// Register ECharts components
echarts.use([
  PieChart,
  BarChart,
  LineChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  CanvasRenderer
])

const userStore = useUserStore()
const drugStore = useDrugStore()
const checkStore = useCheckStore()
const orderStore = useOrderStore()

let charts = []

onMounted(async () => {
  try {
    await Promise.all([
      initUserChart(),
      initRevenueChart(),
      initDrugChart(),
      initTreatmentChart(),
      initChecksChart()
    ])
    
    window.addEventListener('resize', handleResize)
  } catch (error) {
    console.error('Failed to initialize charts:', error)
  }
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)
  charts.forEach(chart => {
    chart.dispose()
  })
  charts = []
})

function handleResize() {
  charts.forEach(chart => {
    chart.resize()
  })
}

async function initUserChart() {
  try {
    const stats = await userStore.getUserStats()
    const userChart = echarts.init(document.getElementById('userChart'))
    charts.push(userChart)
    
    userChart.setOption({
      title: {
        text: 'User Distribution',
        left: 'center'
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left',
        data: ['Patients', 'Doctors', 'Admins']
      },
      series: [
        {
          name: 'User Types',
          type: 'pie',
          radius: '50%',
          center: ['50%', '60%'],
          data: [
            { value: stats.patients, name: 'Patients' },
            { value: stats.doctors, name: 'Doctors' },
            { value: stats.admins, name: 'Admins' }
          ],
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    })
  } catch (error) {
    console.error('Failed to initialize user chart:', error)
  }
}

async function initRevenueChart() {
  try {
    const revenue = await orderStore.getRevenueStats()
    const revenueChart = echarts.init(document.getElementById('revenueChart'))
    charts.push(revenueChart)
    
    revenueChart.setOption({
      title: {
        text: 'Monthly Revenue',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: revenue.months
      },
      yAxis: {
        type: 'value',
        axisLabel: {
          formatter: '¥{value}'
        }
      },
      series: [
        {
          name: 'Revenue',
          type: 'bar',
          data: revenue.values
        }
      ]
    })
  } catch (error) {
    console.error('Failed to initialize revenue chart:', error)
  }
}

async function initDrugChart() {
  try {
    const drugStats = await drugStore.getPopularDrugs()
    const drugChart = echarts.init(document.getElementById('drugChart'))
    charts.push(drugChart)
    
    drugChart.setOption({
      title: {
        text: 'Top 5 Popular Drugs',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: drugStats.map(item => item.name)
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          name: 'Prescriptions',
          type: 'bar',
          data: drugStats.map(item => item.count)
        }
      ]
    })
  } catch (error) {
    console.error('Failed to initialize drug chart:', error)
  }
}

async function initTreatmentChart() {
  try {
    const treatmentStats = await orderStore.getTreatmentStats()
    const treatmentChart = echarts.init(document.getElementById('treatmentChart'))
    charts.push(treatmentChart)
    
    treatmentChart.setOption({
      title: {
        text: 'Monthly Treatment Count',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: ['Treatments'],
        top: 'bottom'
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '10%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: treatmentStats.months
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          name: 'Treatments',
          type: 'line',
          data: treatmentStats.counts,
          areaStyle: {}
        }
      ]
    })
  } catch (error) {
    console.error('Failed to initialize treatment chart:', error)
  }
}

async function initChecksChart() {
  try {
    const checkStats = await checkStore.getPopularChecks()
    const checksChart = echarts.init(document.getElementById('checksChart'))
    charts.push(checksChart)
    
    checksChart.setOption({
      title: {
        text: 'Top Medical Checks',
        left: 'center'
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left',
        data: checkStats.map(item => item.name)
      },
      series: [
        {
          name: 'Medical Checks',
          type: 'pie',
          radius: '55%',
          center: ['50%', '60%'],
          data: checkStats.map(item => ({
            name: item.name,
            value: item.count
          })),
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    })
  } catch (error) {
    console.error('Failed to initialize checks chart:', error)
  }
}
</script>

<style scoped>
.data-visualization {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  margin-top: 10px;
}

.box-card {
  margin-bottom: 20px;
}
</style> 